import { defineStore } from 'pinia';

export const useTaskStore = defineStore('task', {
  state: () => ({
    tasks: [],
    searchQuery: '',
    filter: 'all' // all, completed, pending
  }),
  
  getters: {
    filteredTasks: (state) => {
      let filtered = [...state.tasks];
      
      // 应用搜索过滤
      if (state.searchQuery) {
        const query = state.searchQuery.toLowerCase();
        filtered = filtered.filter(task => 
          task.title.toLowerCase().includes(query) || 
          (task.tags && task.tags.some(tag => tag.toLowerCase().includes(query)))
        );
      }
      
      // 应用状态过滤
      if (state.filter === 'completed') {
        filtered = filtered.filter(task => task.completed);
      } else if (state.filter === 'pending') {
        filtered = filtered.filter(task => !task.completed);
      }
      
      return filtered;
    },
    
    allTasks: (state) => state.tasks,
    completedTasks: (state) => state.tasks.filter(task => task.completed),
    pendingTasks: (state) => state.tasks.filter(task => !task.completed),
    taskCount: (state) => state.tasks.length,
    completedCount: (state) => state.tasks.filter(task => task.completed).length,
    pendingCount: (state) => state.tasks.filter(task => !task.completed).length,
    
    // 按优先级统计
    priorityCounts: (state) => {
      return {
        high: state.tasks.filter(task => task.priority === 'high').length,
        medium: state.tasks.filter(task => task.priority === 'medium').length,
        low: state.tasks.filter(task => task.priority === 'low').length
      };
    }
  },
  
  actions: {
    loadTasks() {
      try {
        const savedTasks = localStorage.getItem('todo-tasks');
        if (savedTasks) {
          this.tasks = JSON.parse(savedTasks);
        } else {
          // 如果没有保存的任务，添加一些示例任务
          this.addDemoTasks();
        }
      } catch (error) {
        console.error('Failed to load tasks:', error);
        this.tasks = [];
      }
    },
    
    saveTasks() {
      try {
        localStorage.setItem('todo-tasks', JSON.stringify(this.tasks));
      } catch (error) {
        console.error('Failed to save tasks:', error);
      }
    },
    
    addTask(task) {
      this.tasks.unshift({
        ...task,
        id: Date.now().toString(),
        completed: false,
        createdAt: new Date().toISOString()
      });
      this.saveTasks();
    },
    
    addDemoTasks() {
      const demoTasks = [
        {
          id: '1',
          title: "完成项目报告",
          tags: ["工作", "文档"],
          priority: "high",
          dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          completed: false,
          createdAt: new Date().toISOString()
        },
        {
          id: '2',
          title: "购买生活用品",
          tags: ["生活", "购物"],
          priority: "medium",
          dueDate: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          completed: false,
          createdAt: new Date().toISOString()
        },
        {
          id: '3',
          title: "锻炼30分钟",
          tags: ["健康", "习惯"],
          priority: "low",
          dueDate: new Date().toISOString().split('T')[0],
          completed: true,
          createdAt: new Date().toISOString()
        },
        {
          id: '4',
          title: "阅读30页书籍",
          tags: ["学习", "阅读"],
          priority: "medium",
          dueDate: "",
          completed: false,
          createdAt: new Date().toISOString()
        }
      ];
      
      this.tasks = [...demoTasks];
      this.saveTasks();
    },
    
    updateTask(updatedTask) {
      const index = this.tasks.findIndex(task => task.id === updatedTask.id);
      if (index !== -1) {
        this.tasks[index] = updatedTask;
        this.saveTasks();
      }
    },
    
    deleteTask(taskId) {
      this.tasks = this.tasks.filter(task => task.id !== taskId);
      this.saveTasks();
    },
    
    toggleTaskCompleted(taskId) {
      const task = this.tasks.find(task => task.id === taskId);
      if (task) {
        task.completed = !task.completed;
        this.saveTasks();
      }
    },
    
    clearCompletedTasks() {
      this.tasks = this.tasks.filter(task => !task.completed);
      this.saveTasks();
    },
    
    // 批量操作
    batchToggleCompleted(ids, completed) {
      this.tasks = this.tasks.map(task => 
        ids.includes(task.id) ? { ...task, completed } : task
      );
      this.saveTasks();
    },
    
    batchUpdatePriority(ids, priority) {
      this.tasks = this.tasks.map(task => 
        ids.includes(task.id) ? { ...task, priority } : task
      );
      this.saveTasks();
    },
    
    batchDelete(ids) {
      this.tasks = this.tasks.filter(task => !ids.includes(task.id));
      this.saveTasks();
    },
    
    setSearchQuery(query) {
      this.searchQuery = query;
    },
    
    setFilter(filter) {
      this.filter = filter;
    }
  }
});
    